// wwwroot/js/http.js

export const http = {
    async get(url) {
        return this.request(url, 'GET');
    },

    async post(url, data) {
        return this.request(url, 'POST', data);
    },

    async request(url, method, body) {
        const token = sessionStorage.getItem('token');

        const options = {
            method,
            headers: {
                'Content-Type': 'application/json',
                ...(token ? { 'Authorization': 'Bearer ' + token } : {})
            }
        };

        if (body) {
            options.body = JSON.stringify(body);
        }

        try {
            const res = await fetch(url, options);

            let result;
            try {
                result = await res.json();
            } catch (e) {
                result = { code: res.status, message: res.statusText };
            }

            if (!res.ok || result.code !== 200) {
                throw new Error(result.message || '请求失败');
            }

            return result.data;
        } catch (error) {
            console.error(`[HTTP] 请求异常：${url}`, error);
            alert(error.message || '网络异常，请重试');
            throw error;
        }
    }
};
